/**
 * 
 */
package kr.co.insoft.auth.service.initalize.impl;

import kr.co.insoft.auth.mapper.codec.WeeklyCodecKeyMapper;
import kr.co.insoft.auth.mapper.initialize.InitializeTableMapper;
import kr.co.insoft.auth.mapper.mail.MaillingMapper;
import kr.co.insoft.auth.mapper.security.UserDetailsMapper;
import kr.co.insoft.auth.model.initialize.InitializeTableModel;
import kr.co.insoft.auth.service.initalize.InitializeTableService;
import kr.co.insoft.framework.exceptions.ExceptionCode;
import kr.co.insoft.framework.exceptions.ServiceException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author IN-SOFT Inc. GoodwillDD(sylee@in-soft.co.kr)
 * 
 */
@Service
public class InitializeTableServiceImpl implements InitializeTableService {

	String datasource;

	@Autowired
	WeeklyCodecKeyMapper codecKeyMapper;

	@Autowired
	UserDetailsMapper userDetailsMapper;

	@Autowired
	MaillingMapper maillingMapper;

	@Override
	@Transactional(rollbackFor=ServiceException.class)
	public void initializeTables() throws ServiceException {
		try {
			runInitalize(codecKeyMapper, new InitializeTableModel(datasource,
					CODEC_SALT_TABLE));
			runInitalize(userDetailsMapper, new InitializeTableModel(
					datasource, USERS_TABLE));
			runInitalize(maillingMapper, new InitializeTableModel(datasource,
					MAILLING));
		} catch (Exception e) {
			throw new ServiceException(ExceptionCode.SERVICE_EXCEPTION, e);
		}
	}

	private void runInitalize(InitializeTableMapper mapper,
			InitializeTableModel initializeTableModel) throws ServiceException {
		try {
			switch (mapper.isExistTable(initializeTableModel)) {
			case 0:
				mapper.createTable();
			default:
			}
		} catch (Exception e) {
			throw new ServiceException(ExceptionCode.SERVICE_EXCEPTION, e);
		}
	}

	/**
	 * @return the datasource
	 */
	public String getDatasource() {
		return datasource;
	}

	/**
	 * @param datasource
	 *            the datasource to set
	 */
	public void setDatasource(String datasource) {
		this.datasource = datasource;
	}
}
